package com.jimmy.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.jimmy.reggie.common.BaseContext;
import com.jimmy.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录的拦截器，进行过滤拦截，对静态资源的访问进行
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter" ,urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * JavaWeb里面的那个过滤器，直接看路径里面有没有，contains，没有的话就处理
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse res= (HttpServletResponse) response;
        String requestURI = req.getRequestURI();
        String[] urls={
                "/employee/login"
                ,"/employee/logout"
                ,"/backend/**"
                ,"/front/**"
                ,"/common/**"
                ,"/user/sendMsg"
                ,"/user/login"
                ,"/doc.html"
                ,"/webjars/**"
                ,"/swagger-resources"
                ,"/v2/api-docs"
        };
        log.info("拦截到"+requestURI);
        boolean flag = check(urls, requestURI);
        //这里连续的if判断，就好像筛子一样的过滤，精准而优雅的代码风格，肯定不是我写的，嘿嘿
        if (flag){
            log.info("不需要处理的请求");
            chain.doFilter(req,res);
            log.info("无需处理的请求，已经放行");
            return;
        }
        log.info("需要处理的请求");
        if (req.getSession().getAttribute("employee")!=null){
            BaseContext.setCurrentId((Long) req.getSession().getAttribute("employee"));
            chain.doFilter(req,res);
            /*
              这个return一定要添加，否则登录成功放行后，会回到这里，会继续执行下面的代码
              然后就会出现响应重复的问题
             */
            return;
        }
        if(req.getSession().getAttribute("user")!=null){
            log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("user"));
            BaseContext.setCurrentId((Long) req.getSession().getAttribute("user"));
            chain.doFilter(req,res);
            return;
        }
        log.info("用户未登录");
        res.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return match;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
